# !/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'Liu DengFeng、Du Fei'

from flask import Flask, request, jsonify
import os

from api.captchaSolver.b64_images import Images
from api.captchaSolver.cv2_distance import generate_distance

from api.uploadChunks.upload_service import save_chunk, merge_chunks, delete_path, is_all_chunks_uploaded, get_file_base64

app = Flask(__name__)


@app.route('/captchaSolver', methods=['POST'])
def captcha_solver():
    req_json = request.get_json()
    imgs = Images(req_json['capcode'], req_json['slidingImage'], req_json['backImage'], req_json['yHeight'])
    return generate_distance(imgs.slidingImage, imgs.backImage)


# 文件上传主目录
UPLOAD_FOLDER = "uploads"
# 临时存储分片的目录
TEMP_FOLDER = os.path.join(UPLOAD_FOLDER, "temp")
os.makedirs(TEMP_FOLDER, exist_ok=True)
@app.route("/uploadChunks", methods=["POST"])
def upload_chunk():
    """
    接收客户端上传的分片数据并存储，
    在所有分片上传完成后合并成完整的文件。
    """
    # 从请求中提取必要的元数据
    key = request.form.get("key")  # 当前分片对应的属性名
    chunk_index = int(request.form.get("chunk_index", -1))  # 当前分片的索引
    total_chunks = int(request.form.get("total_chunks", -1))  # 总分片数量
    data = request.files.get("data") or request.form.get("data")  # 分片数据

    if not key or chunk_index == -1 or total_chunks == -1 or not data:
        return jsonify({"error": "Invalid request"}), 400

    # 文件标识符（例如通过用户会话或文件 ID 区分不同文件）
    file_id = request.form.get("file_id", "default_file")

    # 保存当前分片
    temp_key_folder = save_chunk(key, file_id, chunk_index, data, TEMP_FOLDER)

    # 检查是否所有分片已上传
    if is_all_chunks_uploaded(temp_key_folder, total_chunks):
        # 合并所有分片
        merge_chunks(key, file_id, total_chunks, TEMP_FOLDER, UPLOAD_FOLDER)
        # 删除所有分片
        delete_path(os.path.join(TEMP_FOLDER, file_id))
        return jsonify({"message": f"Key '{key}' uploaded successfully"}), 200

    return jsonify({"message": f"Chunk {chunk_index + 1}/{total_chunks} for key '{key}' uploaded"}), 200


@app.route('/zgpCaptchaSolver', methods=['POST'])
def zgp_captcha_solver():
    req_json = request.get_json()
    file_id = req_json['fileId']

    slidingImage_path = os.path.join(UPLOAD_FOLDER, f"{file_id}_slidingImage")
    backImage_path = os.path.join(UPLOAD_FOLDER, f"{file_id}_backImage")

    slidingImage_b64 = get_file_base64(slidingImage_path)
    backImage_b64 = get_file_base64(backImage_path)

    # 删除所有已读取的文件
    delete_path(slidingImage_path)
    delete_path(backImage_path)

    if slidingImage_b64 and backImage_b64:
        return generate_distance(slidingImage_b64, backImage_b64)

    return {}